package yns.controller.exam;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import yns.entity.User;
import yns.service.ServiceExam1;

@Controller
public class ControllerExam1 {
	
	public static final String exam1= "jsp/exam1";

	//service 注解方式注入
	@Resource(name = "serviceExam1")
	private ServiceExam1 serviceExam1;

	//返回指定内容，jsp中以${key}显示
	@RequestMapping(value = "/exam1")
	public ModelAndView exam1() {
		System.out.println("exam1");
		ModelAndView mv = new ModelAndView();

		mv.addObject("message", "<a>Hello World!</a>");
		mv.addObject("message2", "name");

		mv.setViewName(exam1);
		System.out.println(serviceExam1.getMessage());
		return mv;
	}
	
	//只接受POST请求，非POST请求会报错。映射到指定实体，每个属性对应提交的对象的Name属性
	@RequestMapping(value = "/exam2",method = RequestMethod.POST)
	public ModelAndView exam2(@ModelAttribute("user") User user) {
		System.out.println("exam2");
		ModelAndView mv = new ModelAndView();
		
		mv.addObject("name", user.getName());
		mv.addObject("age", user.getAge());
		mv.addObject("sex", user.getSex());
	
		mv.setViewName(exam1);
		System.out.println(user.toString());
		return mv;
	}

	//指定请求变量非必须,如果没有设置defaultValue则对应变量返回null
	@RequestMapping(value = "/exam3")
	@ResponseBody
	public String exam3(
			@RequestParam(value = "name", required = false, defaultValue = "Default") String name,
			@RequestParam(value = "age", required = false) String age) {
		
		System.out.println("exam3");
		System.out.println(name);
		System.out.println(age);
		
		if (name == null) {
			name = "Default value for exam3 : name";
		}
		if (age == null) {
			age = "Default value for exam3 : age";
		}
		
		return name + " " + age;
	}
	
	//指定请求变量（必须，没有会报400错）
	@RequestMapping(value = "/exam4")
	@ResponseBody
	public String exam4(@RequestParam(value = "name") String name)  {
		System.out.println("exam4");
		
		if (name == null) {
			name = "Default value for exam4";
		}
		System.out.println(name);
		return name;
	}
	
	//指定URLParam,缺少会报400错
	@RequestMapping(value = "/exam5/{urlParam}")
	@ResponseBody
	public String exam5(@PathVariable(value = "urlParam") String urlParam) {
		System.out.println("exam5");
		
		System.out.println(urlParam);
		
		return urlParam;
		
	}
	
	//URLParam可以指定多个,缺少会报400错
	@RequestMapping(value = {"/exam6/{urlParam}/param/{urlParam2}"})
	@ResponseBody
	public String exam6(@PathVariable(value = "urlParam") String urlParam,
			@PathVariable(value = "urlParam2") String urlParam2) {
		System.out.println("exam6");
		
		System.out.println(urlParam);
		System.out.println(urlParam2);
		
		return urlParam + " " + urlParam2;
	}
	
	
	//多个路径映射到同一个方法,Redirect重定向到main
	//多个路径如果直接重定向到页面，需要注意相对路径变化
	@RequestMapping(value = {"/exam7", "/exam7/param"})
	@ResponseBody
	public ModelAndView exam7(HttpServletRequest request) {
		System.out.println("exam7");
		System.out.println(request.getRequestURI());
		
		String requestURI = request.getRequestURI();
		ModelAndView modelAndView;
		if (requestURI.indexOf("param") > -1) {
			modelAndView = new ModelAndView(new RedirectView("../main"));
		}
		else {
			modelAndView = new ModelAndView(new RedirectView("main"));
		}
		return modelAndView;
	}
	
	//Forward重定向到main
	@RequestMapping(value = {"/exam8"})
	@ResponseBody
	public void exam8(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		System.out.println("exam8");
		request.getRequestDispatcher("main").forward(request, response); 
	}
	
	//接受参数中有create参数的请求
	@RequestMapping(value = {"/exam9"},params="create")
	@ResponseBody
	public String exam9() {
		System.out.println("exam9");
		return "exam9";
	}
	
	//接受参数中没有create参数的请求
	@RequestMapping(value = {"/exam10"},params="!create")
	@ResponseBody
	public String exam10() {
		System.out.println("exam10");
		return "exam10";
	}
	
	//接受参数中有submitFlag参数且value为create的请求
	@RequestMapping(value = {"/exam11"},params="submitFlag=create")
	@ResponseBody
	public String exam11() {
		System.out.println("exam11");
		return "exam11";
	}
	
	
	
	@RequestMapping(value = "/upload")  
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {  
        System.out.println("开始");  
        String path = request.getSession().getServletContext().getRealPath("upload");  
        String fileName = file.getOriginalFilename();  
//        String fileName = new Date().getTime()+".jpg";  
        System.out.println(path);  
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
  
        return "result";  
    }  

}
